<template>
  <div id="student">
    <!-- 顶部导航 -->
    <el-row class="padding-50">
      <el-col :span="24">
        <ul class="list">
          <li class="logo"><i class="iconfont icon-kaoshi"></i><span>DORO-Learning-Online</span></li>
          <li><a href="javascript:;" @click="goCourse">我的课程</a></li>
          <li><a href="javascript:;" @click="exam">我的考试</a></li>
          
          <li class="logo">我的消息</li>
          <li class="right" @mouseenter="flag = true" @mouseleave="flag = false">
            <a href="javascript:;"><i class="iconfont icon-Userselect icon"></i>{{ user.userName }}</a>
            <div class="msg" v-if="flag">
              <p @click="manage">管理中心</p>
              <p class="exit" @click="exit">退出</p>
            </div>
          </li>
        </ul>
      </el-col>
    </el-row>

    <!-- 主体内容 -->
    <div class="main-container">
      <!-- 左侧发送消息 -->
      <div class="send-box">
        <h3>发送新消息</h3>
        <el-form :model="sendForm" label-width="80px">
          <el-form-item label="接收者ID">
            <el-input v-model="sendForm.receiverID" placeholder="输入接收者ID" />
          </el-form-item>
          <el-form-item label="标题">
            <el-input v-model="sendForm.title" placeholder="输入标题" />
          </el-form-item>
          <el-form-item label="内容">
            <el-input type="textarea" v-model="sendForm.content" rows="3" placeholder="输入消息内容" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="sendMessage">发送</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 右侧消息列表 -->
      <div class="notice-list">
        <div class="title">我的消息</div>

        <!-- 搜索框 -->
        <div style="margin-bottom: 10px;">
          <el-input
    v-model="searchKeyword"
    placeholder="按标题或发送者搜索"
    clearable
    @input="filterMessages"
    style="width: 300px"
  >
    <template #prefix><i class="el-icon-search" /></template>
  </el-input>
        </div>

        <ul class="notice-wrapper" v-loading="loading">
          <li
            class="notice-item"
            v-for="(item, index) in filteredList"
            :key="index"
            @click="loadMessageDetail(item.id)"
          >
            <div class="notice-title">{{ item.title }}</div>
            <div class="notice-meta">
              <span class="sender">来自：{{ item.senderName }}（ID：{{ item.senderID }}）</span>
              <span class="time">{{ formatTime(item.timestamp) }}</span>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <!-- 消息详情弹窗 -->
    <el-dialog
  v-model="dialogVisible"
  title="消息详情"
  width="500px"
  :close-on-click-modal="false"
>
  <div class="dialog-section">
    <span class="dialog-label">标题：</span>{{ selectedMessage.title }}
  </div>
  <div class="dialog-section">
    <span class="dialog-label">来自：</span>{{ selectedMessage.senderName }}（ID：{{ selectedMessage.senderID }}）
  </div>
  <div class="dialog-section">
    <span class="dialog-label">时间：</span>{{ formatTime(selectedMessage.timestamp) }}
  </div>
  <div class="dialog-section">
    <span class="dialog-label">内容：</span>
  </div>
  <div class="dialog-content">
    {{ selectedMessage.content }}
  </div>
</el-dialog>

    <v-footer />
  </div>
</template>

<script>
import myFooter from "@/components/student/myFooter"

export default {
  components: {
    "v-footer": myFooter
  },
  data() {
    return {
      flag: false,
      user: {},
      noticeList: [],
      filteredList: [],      // 过滤后的消息
      loading: false,
      dialogVisible: false,
      selectedMessage: {},
      sendForm: {
        receiverID: '',
        title: '',
        content: ''
      },
      searchKeyword: ''      // 搜索关键词
    }
  },
  created() {
    this.userInfo()
    this.loadMessages()
  },
  methods: {
    userInfo() {
      const name = this.$cookies.get("cname")
      const id = this.$cookies.get("cid")
      this.user.userName = name
      this.user.studentId = id
    },
    formatTime(time) {
      return time ? new Date(time).toLocaleString() : "未知时间"
    },
    loadMessages() {
  this.loading = true
  const userId = this.user.studentId
  this.$axios.get(`/api/notice/received`, { params: { userID: userId } })
    .then(res => {
      if (res.data.code === 200) {
        this.noticeList = res.data.data
        this.filteredList = this.noticeList // 初始化显示全部
      } else {
        this.$message.error("消息加载失败")
      }
    })
    .catch(err => {
      console.error(err)
      this.$message.error("请求出错")
    })
    .finally(() => {
      this.loading = false
    })
},

    sendMessage() {
      const { receiverID, title, content } = this.sendForm
      const senderID = this.user.studentId
      if (!receiverID || !title || !content) {
        this.$message.warning("请填写完整信息")
        return
      }

      this.$axios.post('/api/notice/add', {
        senderID,
        receivers: [Number(receiverID)],
        title,
        content
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success("发送成功")
          this.sendForm = { receiverID: '', title: '', content: '' }
          this.loadMessages()
        } else {
          this.$message.error("发送失败：" + res.data.msg)
        }
      }).catch(err => {
        console.error(err)
        this.$message.error("请求出错")
      })
    },
    loadMessageDetail(id) {
      this.$axios.get(`/api/notice/id`, { params: { id } })
        .then(res => {
          if (res.data.code === 200) {
            this.selectedMessage = res.data.data
            this.dialogVisible = true
          } else {
            this.$message.error("加载详细消息失败")
          }
        })
        .catch(err => {
          console.error(err)
          this.$message.error("请求出错")
        })
    },
    filterMessages() {
    const keyword = this.searchKeyword.trim().toLowerCase()
    if (!keyword) {
      this.filteredList = this.noticeList
    } else {
      this.filteredList = this.noticeList.filter(msg =>
        msg.title.toLowerCase().includes(keyword) ||
        msg.senderName.toLowerCase().includes(keyword)
      )
    }
  },
    searchMessage() {
      const id = this.searchID.trim()
      if (!id || isNaN(id)) {
        this.$message.warning("请输入有效的消息ID")
        return
      }
      this.loadFullMessage(id)
    },
    exit() {
      this.$cookies.remove("cname")
      this.$cookies.remove("cid")
      this.$router.push("/")
    },
    manage() {
      this.$router.push("/student/manager")
    },
    goCourse() {
      this.$router.push("/student")
    },
    exam() {
      this.$router.push("/student/exam")
    },
    AI() {
      this.$router.push("/student/AIhelper")
    }
  }
}
</script>

<style scoped>
/* 样式保持原样，此处略过（你已处理得很好） */
</style>


<style scoped>
/* 顶部导航样式 */
#student .padding-50 {
  margin: 0 auto;
  padding: 0 50px;
  box-shadow: 0 0 10px 4px rgba(1, 149, 255, 0.1);
  background-color: #fff;
}
.list a {
  text-decoration: none;
  color: #334046;
}
li {
  list-style: none;
  height: 60px;
  line-height: 60px;
}
#student .list {
  display: flex;
}
#student .list li {
  padding: 0 20px;
  cursor: pointer;
}
#student .list li:hover {
  background-color: #0195ff;
  transition: all 0.3s ease;
}
#student .list li:hover a {
  color: #fff;
}
#student .list .right {
  margin-left: auto;
  position: relative;
}
#student .list .right .msg {
  text-align: center;
  position: absolute;
  top: 60px;
  left: 0px;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-bottom: 3px solid #0195ff;
}
.right .msg p {
  height: 40px;
  line-height: 40px;
  width: 105px;
}
.right .msg p:hover {
  background-color: #0195ff;
}
#student .list .logo {
  display: flex;
  font-weight: bold;
  color: #2f6c9f;
}
#student .list .logo i {
  font-size: 50px;
}

/* 主体布局 */
.main-container {
  display: flex;
  justify-content: space-between;
  width: 1000px;
  margin: 30px auto;
  gap: 20px;
}

/* 左侧消息发送表单 */
.send-box {
  width: 300px;
  padding: 16px;
  height:300px;
  border: 1px solid #eee;
  border-radius: 6px;
  background-color: #f8f8f8;
}

/* 右侧消息列表 */
.notice-list {
  flex: 1;
}
.notice-list .title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}
.notice-wrapper {
  display: flex;
  flex-direction: column;
  gap: 40px;
}
.notice-item {
  padding: 12px 16px;
  border: 1px solid #eee;
  border-radius: 6px;
  background-color: #fafafa;
  transition: all 0.3s ease;
  cursor: pointer;
}
.notice-item:hover {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}
.notice-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 4px;
}
.notice-meta {
  font-size: 13px;
  color: #888;
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}
.notice-content {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/* 保证每条消息都完整显示 */
.notice-content {
  font-size: 14px;
  color: #333;
  white-space: normal; /* 允许自动换行 */
  overflow: visible;
  text-overflow: initial;
  display: block;
}

/* 调整弹窗中标题、来源等格式 */
.dialog-section {
  margin-bottom: 10px;
  font-size: 14px;
  color: #333;
  text-align: left;
}
.dialog-label {
  font-weight: bold;
  display: inline-block;
  margin-right: 5px;
}
.dialog-content {
  white-space: pre-wrap;
  word-break: break-word;
  padding: 10px;
  background: #f8f8f8;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
  text-align: left;
}
/**/

</style>
